package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.base.PageView;
import org.gdpu.model.*;
import org.gdpu.service.ExaminationService;
import org.gdpu.service.ExaminerService;
import org.gdpu.service.PersonService;
import org.gdpu.vo.ExaminationVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;


@Component("examination")
@Scope("prototype")
public class ExaminationAction extends MyActionSupport implements ModelDriven<ExaminationVO> {

    private static final Logger logger = LogManager.getLogger(ExaminationAction.class);

    private final ExaminationVO examinationVO = new ExaminationVO();
    private ExaminationService examinationService;
    private ExaminerService examinerService;
    private PersonService personService;

    public String getList(){
        int maxResult = 10000;
        int firstIndex = 0;
        PageView<Examination> pageView = new PageView<Examination>(maxResult,1);
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "desc");

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.owner = ?1)");
        params.add(examinationVO.getAccount());


        pageView.setQueryResult(examinationService.getScrollData(Examination.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        examinationVO.setPageView(pageView);
        view = "/page/examination/examinationList.jsp";
        return VIEW;
    }

    public String myList(){
        examinationVO.setExaminations(examinationService.findExamination(examinationVO.getAccount()));
        view = "/page/examination/myExamination.jsp";
        return VIEW;
    }

    public String changeExaminationState(){
        String state = examinationVO.getState();
        ExaminationState examinationState = ExaminationState.CANCEL;
        if("PROCESS".equals(state)){
             examinationState = ExaminationState.END;
        }else if("PREPARE".equals(state)){
             examinationState = ExaminationState.PROCESS;
        }
        Examination examination = null;
        try {
            examination = examinationService.find(Examination.class,examinationVO.getId());
        } catch (Exception e) {
            examinationVO.setResultMessage("考试有误,请稍后再试!");
            return ERROR;
        }
        examination.setExaminationState(examinationState);
        examinationService.update(examination);

        int maxResult = 10000;
        int firstIndex = 0;
        PageView<Examination> pageView = new PageView<Examination>(maxResult,1);
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "desc");

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.owner = ?1)");
        params.add(examinationVO.getAccount());


        pageView.setQueryResult(examinationService.getScrollData(Examination.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        examinationVO.setPageView(pageView);
        view = "/page/examination/examinationList.jsp";
        return VIEW;
    }

    public String beginExamination(){
        Examination examination = null;
        try {
            examination = examinationService.find(Examination.class,examinationVO.getId());
        } catch (Exception e) {
            examinationVO.setResultMessage("考试有误,请稍后再试!");
            return ERROR;
        }
        Person person =  personService.findPersonByAccout(examinationVO.getAccount());
        Examiner examiner = examinerService.findExaminerByAccout(person, examination);
        if(examiner.getExamBeginTime() == null||"".equals(examiner.getExamBeginTime().toString())){
            examiner.setExamBeginTime(new Date());
            examinerService.update(examiner);
        }
        examinationVO.setExaminer(examiner);
        examinationVO.setExamination(examination);

        TestPaperInfo testPaperInfo =  examination.getTestPaperInfo();

        int maxResult = 10000;
        int firstIndex = 0;
        PageView<TestPaper> pageView = new PageView<TestPaper>(maxResult,1);
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("test.category.id", "asc");

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.testPaperInfo.id = ?1)");
        params.add(testPaperInfo.getId());

        pageView.setQueryResult(examinationService.getScrollData(TestPaper.class, firstIndex, maxResult,
                jpql.toString(),params.toArray(), orderBy));

        List<TestPaper> testPapers = pageView.getRecords();
        for(TestPaper testPaper : testPapers){
            Test test = testPaper.getTest();
            test.setTheme(test.getTheme().replaceAll("\\r\\n", "").replaceAll("\\t", "&nbsp;&nbsp;"));
            TestAnswer testAnswer = test.getAnswer();
            testAnswer.setAnswer(testAnswer.getAnswer().replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "&nbsp;&nbsp;"));
            test.setAnswer(testAnswer);
            testPaper.setTest(test);
        }
        pageView.setRecords(testPapers);

        examinationVO.setPageView(pageView);
        examinationVO.setTestPaperInfo(testPaperInfo);
        view = "/page/examination/examing.jsp";
        return VIEW;
    }

    @Override
    public String execute() {

        if ("".equals(examinationVO.getSubject())) {
            examinationVO.setResultMessage("请选择考试科目!");
            return ERROR;
        }

        if ("".equals(examinationVO.getType())) {
            examinationVO.setResultMessage("请选择考试类型!");
            return ERROR;
        }

        if (examinationVO.getName().isEmpty() || examinationVO.getExamBeginTime().isEmpty() || examinationVO.getExamEndTime().isEmpty()) {
            examinationVO.setResultMessage("请确认必要信息输入正常!");
            return ERROR;
        }
        boolean openTestPaper = examinationVO.getOpenTestPaper() == 1;
        boolean openScore = examinationVO.getOpenScore() == 1;
        String desc = examinationVO.getDescription();
        //TODO:从班级生成考生
        Examination examination = examinationService.createExamination(examinationVO.getName(), desc,
                examinationVO.getSubject(), examinationVO.getExamBeginTime(), examinationVO.getExamEndTime(),
                examinationVO.getAdvanceTime(), examinationVO.getTime(), examinationVO.getType(),
                examinationVO.getMode(), openTestPaper, openScore, examinationVO.getTeamName(),examinationVO.getTestPaper(),examinationVO.getCreator());

        if ("ERROR".equals(examination.getName())) {
            examinationVO.setResultMessage("组别在该时间段已有考试，请重新选择时间！");
            return ERROR;
        } else if (examination != null) {
            logger.info("create Examination by " + examinationVO.getCreator() + "! Examination_id:" + examination.getId());
            examinationVO.setResultMessage("考试创建成功！<br/>具体信息如下：<br/>" + examination + "<br/>如需修改请联系管理员！谢谢合作");
            return SUCCESS;
        } else {
            examinationVO.setResultMessage("输入信息有误！");
            return ERROR;
        }
    }

    @Resource(name = "examinationServiceImpl")
    public void setExaminationService(ExaminationService examinationService) {
        this.examinationService = examinationService;
    }

    @Resource(name = "examinerServiceImpl")
    public void setExaminerService(ExaminerService examinerService) {
        this.examinerService = examinerService;
    }
    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @Override
    public ExaminationVO getModel() {
        return examinationVO;
    }
}
